//
//  CityNameViewController.m
//  MagazineShangejie
//
//  Created by wen on 16/2/15.
//  Copyright © 2016年 CnbizMedia. All rights reserved.
//

#import "CityNameViewController.h"
#import "ChineseString.h"
#import "Util.h"
#import "TableViewController.h"
@interface CityNameViewController (){

    UIButton*button;
    TableViewController *table;
    
    NSMutableArray *titleArray;
}

@end

@implementation CityNameViewController
@synthesize indexArray;
@synthesize LetterResultArr;

- (void)viewDidLoad
{
    self.title = @"城市切换";
    [super viewDidLoad];
    
    //获取保存到单例的本地城市的名字
    NSArray *stringsToSort2 = [NSArray arrayWithArray:[UserDefaults objectForKey:@"cityNameArray"]];
    NSLog(@"stringsToSort2 --- %@",stringsToSort2);
    NSMutableArray *cityNameArr  =[[NSMutableArray alloc] init];
    
    for (int i=0; i < [stringsToSort2 count]; i++) {
        NSString *cityString = stringsToSort2 [i][@"catname"];
        [cityNameArr addObject:cityString];
        NSLog(@"cityNameArr --- %@",cityNameArr);
    }
    
    NSArray *stringsToSort=[NSArray arrayWithArray:cityNameArr];
    titleArray = [[NSMutableArray alloc]init];
//    NSArray *stringsToSort=[NSArray arrayWithObjects:
//                            @"￥hhh, .$",@" ￥Chin ese ",@"开源中国 ",@"www.oschina.net",
//                            @"开源技术",@"社区",@"开发者",@"传播",@"重庆",
//                            @"2014",@"2013",@"100",@"中国",@"暑假作业",
//                            @"键盘", @"鼠标",@"hello",@"world",@"world",@"199",@"911",@"hello word",@"北京",@"成都",@"南京", @"上海",@"台湾",@"东京",@"电脑",
//                            @"显示器",
//                            @"你好",
//                            @"推特",
//                            @"乔布斯",
//                            @"再见",
//                            @"暑假作业",
//                            @"键盘",
//                            @"鼠标",
//                            @"谷歌",
//                            @"苹果", ,@"郑州",@"苏州",@"北京",@"成都",@"南京", @"上海",@"台湾",@"东京",@"电脑"                           nil];
    NSMutableArray *nowCityArray = [[NSMutableArray alloc]init];
    NSString *nowTheCityName = [UserDefaults objectForKey: @"nowTheCity"];
    if (nowTheCityName.length > 1) {
        nowCityArray = [NSMutableArray arrayWithObjects:nowTheCityName, nil];
    }
    else{
        nowCityArray = [NSMutableArray arrayWithObjects:@"您没有打开定位，请在开启后尝试", nil];
    }
    
    NSMutableArray *loveCityArray = [[NSMutableArray alloc]init];
//    [NSMutableArray arrayWithObjects:@"重庆", nil];
    
    self.indexArray = [ChineseString IndexArray:stringsToSort];
    titleArray = [indexArray mutableCopy];
    
    [titleArray insertObject:@"您当前的城市可能是" atIndex:0];
    [titleArray insertObject:@"经常选择的城市" atIndex:1];
 
    [self.indexArray insertObject:@"#" atIndex:0];
    self.LetterResultArr = [ChineseString LetterSortArray:stringsToSort];
    
    
        if ([UserDefaults objectForKey:@"loveCityArray"]) {
            
            NSMutableArray *oldLoveCityArray = [NSMutableArray arrayWithArray:[UserDefaults objectForKey:@"loveCityArray"]];
            NSMutableArray *newLoveCityArray = [NSMutableArray arrayWithArray:oldLoveCityArray];

            for (int i = 0; i < newLoveCityArray.count; i++) {
                [loveCityArray insertObject:newLoveCityArray[i][@"catname"] atIndex:i];
                }
        }
        else{
            [loveCityArray addObject:@"重庆"];
        }

    
    [self.LetterResultArr insertObject:nowCityArray atIndex:0];
    [self.LetterResultArr insertObject:loveCityArray atIndex:1];
    
    NSLog(@"LetterResultArr == %@",LetterResultArr);
    
//    button=[UIButton buttonWithType:UIButtonTypeCustom];
//    [button setFrame:CGRectMake(0, 44, self.view.frame.size.width, self.view.frame.size.height)];
//    [button setAlpha:0];
//    [button setBackgroundColor:[UIColor colorWithWhite:0.000 alpha:0.250]];
//    [button addTarget:self action:@selector(resignFirst) forControlEvents:UIControlEventTouchUpInside];
//    [self.view addSubview:button];
//    
    
    UIButton *buttonf=[UIButton buttonWithType:UIButtonTypeCustom];
    [buttonf setFrame:CGRectMake(0, 0, 22, 22)];
    [buttonf addTarget:self action:@selector(popOfDismss) forControlEvents:UIControlEventTouchUpInside];
    [buttonf setImage:[UIImage imageNamed:@"dismiss"] forState:UIControlStateNormal];
    UIBarButtonItem*leftBarItem = [[UIBarButtonItem alloc]initWithCustomView:buttonf];
    self.navigationItem.leftBarButtonItem=leftBarItem;
    ////添加返回手势
    UISwipeGestureRecognizer *recognizer = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(handleSwipeFrom:)];
    [recognizer setDirection:(UISwipeGestureRecognizerDirectionRight)];
    [[self view] addGestureRecognizer:recognizer];

}


-(void)handleSwipeFrom:(UISwipeGestureRecognizer *)recognizer{
    
    if(recognizer.direction==UISwipeGestureRecognizerDirectionRight) {
        CATransition*transition=[CATransition animation];
        transition.duration=1;
        transition.timingFunction=[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
        transition.type=kCATransitionPush;
        transition.subtype=kCATransitionFromLeft;//方向
        [self.view.layer addAnimation:transition forKey:nil];
        [self popOfDismss];
        //        [self dismissViewControllerAnimated:YES completion:^{
 
        //        }];
        
    }
}
-(void)popOfDismss{
    if ([[self.navigationController viewControllers] count]>=2) {
        [self.navigationController popViewControllerAnimated:YES];
        
    }else{
        
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

#pragma mark -Section的Header的值
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    
    
    NSString *key = [indexArray objectAtIndex:section];
    return key;
    //这个好像没什么用
   
}


#pragma mark - Section header view
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320, 20)];
//    lab.backgroundColor = [UIColor colorWithRed:180 green:180 blue:180 alpha:1];
//    lab.backgroundColor = [UIColor lightGrayColor];
    lab.backgroundColor = [UIColor colorWithRed:0.9 green:0.9 blue:0.9 alpha:1];
    lab.text = [NSString stringWithFormat:@"    %@",[titleArray objectAtIndex:section]];
    lab.textColor = [UIColor lightGrayColor];
    return lab;
}
#pragma mark - row height
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 45.0;
}

#pragma mark -
#pragma mark Table View Data Source Methods
#pragma mark -设置右方表格的索引数组
-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
 
    return indexArray;
}
#pragma mark -
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
    NSLog(@"title===%@",title);
    return index;
}

#pragma mark -允许数据源告知必须加载到Table View中的表的Section数。
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
//    return [indexArray count] + 1;
    return [LetterResultArr count];
}
#pragma mark -设置表格的行数为数组的元素个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [[self.LetterResultArr objectAtIndex:section] count];
}
#pragma mark -每一行的内容为数组相应索引的值
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
 
    tableView.sectionIndexBackgroundColor = [UIColor colorWithRed:0.9 green:0.9 blue:0.9 alpha:1];
    tableView.sectionIndexColor = [UIColor redColor];
    
    
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    
    cell.textLabel.text = [[self.LetterResultArr objectAtIndex:indexPath.section]objectAtIndex:indexPath.row];
    return cell;
}
#pragma mark - Select内容为数组相应索引的值
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"---->%@",[[self.LetterResultArr objectAtIndex:indexPath.section]objectAtIndex:indexPath.row]);
    NSString *indexStr = [NSString stringWithFormat:@"%@",[[self.LetterResultArr objectAtIndex:indexPath.section]objectAtIndex:indexPath.row]];
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                    message:[[self.LetterResultArr objectAtIndex:indexPath.section]objectAtIndex:indexPath.row]
                                                   delegate:nil
                                          cancelButtonTitle:@"YES" otherButtonTitles:nil];
//    [alert show];
    
    //判断本地的城市
     if (indexPath.section==0) {
         NSString *nowCityNameStr = [UserDefaults objectForKey:@"nowTheCity"];
         NSString *cccc = [nowCityNameStr substringToIndex:[nowCityNameStr length] - 1];
         NSLog(@"nowCityNameStr ---=== %@",nowCityNameStr);
         NSLog(@"cccc ---=== %@",cccc);
         
         NSMutableArray *allCityNameArray = [UserDefaults objectForKey:@"allCityNameArray"];
         BOOL inOrOut = [allCityNameArray containsObject:cccc];
         NSLog(@"allCityNameArray -==- %@",allCityNameArray);
         
         NSInteger index = [allCityNameArray indexOfObject:cccc];
         
//         if([roadTitleLab.text rangeOfString:@"qingjoin"].location !=NSNotFound)//_roaldSearchText
//         {
//             NSLog(@"yes");
//         }
//         else
//         {
//             NSLog(@"no");
//         }
         
         
         
         if(index == NSNotFound)
         {
//             对象不在数组中
             
             NSDictionary *quYujjDic = [NSDictionary dictionaryWithObjectsAndKeys:@"\u533a\u57df\u7ecf\u6d4e",@"catname",@"0",@"catid",@"quyujingji",@"catdir",@"",@"items",@"local",@"description",@"",@"image",0, @"sub",nil];
             //设置通知。切换城市
             [[NSNotificationCenter defaultCenter] postNotificationName:@"newChangeCityName" object:self userInfo:quYujjDic ];

         }
         
         else {
             //找到本地城市所在数组的地址
             NSArray *stringsToSort2 = [NSArray arrayWithArray:[UserDefaults objectForKey:@"cityNameArray"]];
             NSDictionary *cityDic = stringsToSort2 [index];
             NSLog(@"thecitydic --- %@",cityDic);
             //            table.citySlug = cityDic;
             
             //设置通知。切换城市
             [[NSNotificationCenter defaultCenter] postNotificationName:@"newChangeCityName" object:self userInfo:cityDic ];
             
         
         }
         
         
         if (inOrOut) {
             
         }
         
     }
    
    //
     else{
        //获取保存到单例的本地城市的名字
        NSArray *stringsToSort2 = [NSArray arrayWithArray:[UserDefaults objectForKey:@"cityNameArray"]];
        NSLog(@"stringsToSort2 --- %@",stringsToSort2);
        
        for (int i=0; i < [stringsToSort2 count]; i++) {
            NSString *cityString = stringsToSort2 [i][@"catname"];
            NSLog(@"cityString ---- %@",cityString);
            NSLog(@"indexStr ---- %@",indexStr);
            if ([cityString isEqualToString:indexStr]) {
                NSDictionary *cityDic = stringsToSort2 [i];
                NSLog(@"thecitydic --- %@",cityDic);
    //            table.citySlug = cityDic;
                
                //设置通知。切换城市
                [[NSNotificationCenter defaultCenter] postNotificationName:@"newChangeCityName" object:self userInfo:cityDic ];

                if ([UserDefaults objectForKey:@"loveCityArray"]) {
                    NSMutableArray *oldLoveCityArray = [NSMutableArray arrayWithArray:[UserDefaults objectForKey:@"loveCityArray"]];
                    NSMutableArray *newLoveCityArray = [NSMutableArray arrayWithArray:oldLoveCityArray];
                    
                    for (int a = 0; a < newLoveCityArray.count; a++) {
                        
                        NSString *loveCityString = newLoveCityArray [a][@"catname"];
                        NSLog(@"indexStr ++++ %@",indexStr);
                        NSLog(@"loveCityString ++++ %@",loveCityString);
                        if ([indexStr isEqualToString:loveCityString]) {
                            [self popOfDismss];
                            return;
                        }
                    }
                    
                    if (newLoveCityArray.count > 4) {
     
                        [newLoveCityArray removeObjectAtIndex:4];
                        
                    }
                    
                    [newLoveCityArray insertObject:cityDic atIndex:0];
                    [UserDefaults setObject:newLoveCityArray forKey:@"loveCityArray"];
                }
                else {
                
                    NSMutableArray *loveCityArray = [[NSMutableArray alloc]init];
                    [loveCityArray insertObject:cityDic atIndex:0];
                    [UserDefaults setObject:loveCityArray forKey:@"loveCityArray"];
                    
                }
    //            return;
            }
        }
     }

    [self popOfDismss];

       
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
